<template>
  <div class="category">
    <h1 style="margin-bottom: 20px">{{ this.$route.meta.title }}</h1>
    <el-form ref="category" :model="sizeForm" label-width="120px" size="large">
      <el-form-item label="选择分类">
        <div class="cascader">
          <el-cascader
            :props="props"
            size="large"
            clearable
            placeholder="请选择已经存在的分类"
            v-model="value"
          ></el-cascader>
        </div>
      </el-form-item>
      <el-form-item
        label="新增分类"
        v-if="isUp"
        :rules="[
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change'],
          },
        ]"
      >
        <el-input
          v-model="sizeForm['children']"
          placeholder="如增加一级分类，不要选择已经存在的分类"
        ></el-input>
      </el-form-item>
      <el-form-item size="large">
        <!-- <el-button type="default" @click="add">添加子分类</el-button> -->
        <el-button type="danger" @click="del">删除</el-button>
        <el-button type="warning" @click="updata">修改</el-button>
        <el-button type="primary" @click="onSubmit">上传</el-button>
        <!-- <el-button>取消</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { pinyin } from "pinyin-pro";
export default {
  name: "Category",
  data() {
    return {
      isUp: true,
      sizeForm: {
        children: "",
      },
      options: [],
      value: [],
      props: {
        value: "id",
        checkStrictly: true,
        lazy: true,
        lazyLoad: async (node, resolve) => {
          // console.log(node, "node");
          let level = node.level;
          if (!node.data?.childrens.length > 0) {
            await this.axios.get("/api/v1/category").then((res) => {
              //接口
              const nodes = Array.from(res.data).map((item) => ({
                value: item.value,
                label: item.label,
                id: item._id,
                childrens: item.children,
                leaf: item.children.length < 1,
              }));
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成
              resolve(nodes);
            });
          } else {
            await this.axios
              .get("/api/v1/category/" + node.data?.id)
              .then((res) => {
                //接口
                const nodes = res.data.map((item) => {
                  // console.log(item);
                  return {
                    value: item.value,
                    label: item.label,
                    id: item._id,
                    childrens: item.children,
                    leaf: item.children.length < 1,
                    level: item.deep,
                  };
                });
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                // console.log(nodes, "nodes");
                resolve(nodes);
              });
          }
        },
      },
    };
  },
  methods: {
    updata() {
      let id = this.value[this.value.length - 1];
      let str = pinyin(this.sizeForm.children, { toneType: "none" });
      str = str.replace(/\s/gi, "");
      this.axios
        .get("/api/v1/category/updata/" + id, {
          params: { label: this.sizeForm.children, value: str },
        })
        .then((res) => {
          console.log(res);
          this.msg(res, this);
          if (res.code == 1) {
            // location.reload();
            this.value = "";
            this.sizeForm.children = "";
          }
        });
    },
    del() {
      // console.log(this.value[this.value.length - 1]);
      let id = this.value[this.value.length - 1];
      this.axios.delete("/api/v1/category/" + id).then((res) => {
        // console.log(res);
        if (res.code == 1) {
          this.$message({
            message: res.msg,
            type: "success",
          });
        } else {
          this.$message({
            message: res.msg,
            type: "warning",
          });
        }
        // location.reload();
        this.value = "";
        this.sizeForm.children = "";
      });
    },
    getData(ids) {
      // console.log(ids);
    },
    onSubmit() {
      let str = pinyin(this.sizeForm.children, { toneType: "none" });
      str = str.replace(/\s/gi, "");
      // console.log(this.value, this.sizeForm.children);
      // if(!this.sizeForm.children)
      this.axios
        .get("/api/v1/category/add", {
          params: {
            value: str.toLowerCase(),
            label: this.sizeForm.children,
            children: [],
            id: this.value[this.value.length - 1],
          },
        })
        .then((res) => {
          // console.log(res);
          this.msg(res, this);
          this.value = "";
          this.sizeForm.children = "";
        });
    },
    handleChange() {},
  },
  components: {},
  created() {
    //   console.log(pinyin("你好cs",{toneType: 'none'}));
    this.axios.get("/api/v1/category").then((res) => {
      //初始化分类
      this.options = res.data;
    });
  },
};
/* 
递归插入数据
function add(obj, index = 0) {
        console.log(arr,"arr");
        let has = obj.children.find((item) => {
          // console.log(item,"item");
          // console.log(arr[index + 1],"arr[index + 1]");
          return item.value == value[index + 1];
        });
        if(has){
          if(has.children){
            add(has.children,index+1)
          }else{
            has.children=[];
            has.push({label:""})
          }
        }
        console.log(has, "ss");
      }
      add(first, value); */
</script>
<style scoped>
.cascader div {
  width: 100%;
}
</style>